package model.container;

/**
 * CourseContainer.java
 * Purpose: A container to hold course objects
 * 
 * @author Hans Brems
 * @version 1.0 05/11/2011
 */

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import model.Course;
import model.OfferedCourse;
import model.generator.CourseGenerator;

public class CourseContainer {

	private static CourseContainer courseContainer;

	private List<Course> courses;

	/* Make sure the class cannot be instantiated */
	private CourseContainer() {
		this.courses = new ArrayList<Course>();
		 
	}
	
	public void generateData(){
		courses = CourseGenerator.generateCourses();
	}

	/** Constructs a new course container object if none exists */
	public static CourseContainer getInstance() {
		if (courseContainer == null) {
			courseContainer = new CourseContainer();
		}
		return courseContainer;
	}

	/** Return the list of courses */
	public List<Course> getCourses() {
		return courses;
	}
	
	/** Sets the list of courses */
	public void setCourses(List<Course> courses) {
		this.courses = courses;
	}
	
	/** ?????????????? */
	public void finishInitialisation() {
		CourseGenerator.finishCourseInitialisation();
	}

	/** Returns the number of courses in the container */
	public int getCourseCount() {
		return courses.size();
	}

	/** Clear the container */
	public void clear() {
		courses.clear();
	}

	/** Add a course to the list */
	public void addCourse(Course course) {
		courses.add(course);
	}

	/** Remove a course from the list */
	public void removeCourse(Course course) {
		courses.remove(course);
	}

	/** Prints all courses in the collection */
	public String printAllCourses() {
		String s = new String();
		for (Course course : courses) {
			s += course.toString() + "\n";
		}
		return s;
	}

	/** Searches for a course with a specified ID */
	public Course getCourseByID(int id) {
		for (Course course : this.courses) {
			if (course.getCode() == id) {
				return course;
			}
		}
		return null;
	}
	
	public OfferedCourse getOfferedCourseById(Object id){
		OfferedCourse result = null;
		for(int i=0; i< courses.size(); i++){
			Collection<OfferedCourse> offeredCourses = courses.get(i).getOfferedcourses();
			Iterator<OfferedCourse> offeredCourseIterator = offeredCourses.iterator();
			while(offeredCourseIterator.hasNext() && result == null){
				OfferedCourse offeredCourse = offeredCourseIterator.next();
				if(offeredCourse.getPrimaryKey().equals(id)){
					result = offeredCourse;
				}
			}
		}
		return result;
	}

	public void finishCourseOfferedCourseInitiatialisation() {
		CourseGenerator.finishCourseOfferedCourseRegistrationInitiatialisation();
		
	}
}